import { expect } from '@jest/globals';
import { iconv } from '@ohos/hvigor';
import fse from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { cleanTarget, expectBuildAppError, makeOneHap } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { Project } from '../../plugins/project-builder/models/project-models';
import { ICaseRecord } from '../../plugins/report-builder/report-models';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.FA,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

async function updateConfig(project: Project) {
  // 1. entry模块中的build-profile.json5 设置target
  const entryModuleJsonPath = path.resolve(project.getModule('entry').moduleRootPath(), 'build-profile.json5');
  const jsonBuffer: Buffer = await fse.readFile(entryModuleJsonPath);
  const buildProfileJson = JSON5.parse(iconv.decode(jsonBuffer, 'utf-8'));
  buildProfileJson['targets'] = [
    {
      'name': 'default'
    },
    {
      'name': 'ohosTest'
    },
    {
      'name': 'mini'
    }
  ];
  await fse.writeFile(entryModuleJsonPath, JSON5.stringify(buildProfileJson, null, 2), 'utf-8');

  // 2. 工程级中的build-profile.json5有2个product，且product1包含target-default和mini，product2包含target-default和mini
  const projectModuleJsonPath = path.resolve(project.projectRootPath(), 'build-profile.json5');
  const jsonBuffer1: Buffer = await fse.readFile(projectModuleJsonPath);
  const projectModuleJson = JSON5.parse(iconv.decode(jsonBuffer1, 'utf-8'));

  projectModuleJson['modules'] = [
    {
      'name': 'entry',
      'srcPath': './entry',
      'targets': [
        {
          'name': 'default',
          'applyToProducts': [
            'default'
          ]
        },
        {
          'name': 'mini',
          'applyToProducts': [
            'default'
          ]
        }
      ]
    }
  ];
  await fse.writeFile(projectModuleJsonPath, JSON5.stringify(projectModuleJson, null, 2), 'utf-8');
}

// 2. 选择product-default-entry-default进行菜单栏build-hap构建
// 在entry-build-default目录下生成一个entry-default-hap包和mini目录下生成一个entry-mini-hap包
async function buildHapDefault(project: Project, record: ICaseRecord) {
  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
  });
  const result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('选择product-default-entry-default进行菜单栏build-hap构建 ', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 在entry-build-default目录下生成一个entry-default-hap包和mini目录下生成一个entry-mini-hap包
  const outputs = path.resolve(project.getModule('entry').moduleRootPath(), 'build', 'default', 'outputs');
  const defaultHapExists = await fse.pathExists(path.resolve(outputs, 'default', 'entry-default-unsigned.hap'));
  expect(defaultHapExists).toBe(true);
  const miniHapExists = await fse.pathExists(path.resolve(outputs, 'mini', 'entry-mini-unsigned.hap'));
  expect(miniHapExists).toBe(true);
}


const testFun: TestCaseFun = async (project: Project, taskConfig: TestTaskOption, record: ICaseRecord) => {
  // 修改配置文件
  await updateConfig(project);

  // 1. 选择product-default-entry-default进行make构建 ， make构建成功，在entry-build-default目录下生成一个entry-default-hap包
  await makeOneHap('entry')(project, taskConfig, record);
  await cleanTarget(project);

  // 2. 选择product-default-entry-mini进行make构建 ， make构建成功，在entry-build-mini目录下生成一个entry-mini-hap包
  await makeOneHap('entry', 'default', 'mini')(project, taskConfig, record);
  await cleanTarget(project);

  // 3. 选择product-default-entry-default进行菜单栏build-hap构建
  // build-hap构建成功，在entry-build-default目录下生成一个entry-default-hap包和mini目录下生成一个entry-mini-hap包
  await buildHapDefault(project, record);
  await cleanTarget(project);

  // 4. 选择product-default-entry-default进行菜单栏build-app构建, 构建失败
  await expectBuildAppError()(project, taskConfig, record);
  await cleanTarget(project);

};

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_Visualization_Target_FA_API10_ArkTs_Single_Module_003')
  .description('03.API10-FA单模块工程，1个product，2个target，product包含2个target')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).build())
  .testFun(testFun)
  .load();
